package com.voyager.trip.system.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.voyager.trip.system.dao.SysResourceMapper;
import com.voyager.trip.system.dao.SysUserMapper;
import com.voyager.trip.system.entity.MyGrantedAuthority;
import com.voyager.trip.system.entity.SysResource;
import com.voyager.trip.system.entity.SysUser;

public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	private SysResourceMapper sysResourceMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser user = sysUserMapper.getUserByAccount(username);
		if (user == null) {
			throw new UsernameNotFoundException("账号不存在");
		}
		List<SysResource> authoritys = sysResourceMapper.getResourcesByUserId(user.getId());
		if (authoritys != null && authoritys.size() > 0) {
			user.setAuthorities(authoritys.stream().map(auth -> {
				MyGrantedAuthority myGrantedAuthority = new MyGrantedAuthority();
				myGrantedAuthority.setMethod(auth.getResMethod());
				myGrantedAuthority.setUrl(auth.getResUrl());
				return myGrantedAuthority;
			}).collect(Collectors.toList()));
		}
		return user;
	}

}
